<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员后台 - 手机商城</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f8fafc;
            color: #2c3e50;
            line-height: 1.6;
        }

        .admin-container {
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏 */
        .sidebar {
            width: 250px;
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
        }

        .sidebar-header {
            padding: 2rem 1.5rem;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .admin-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .admin-subtitle {
            opacity: 0.8;
            font-size: 0.9rem;
        }

        .sidebar-nav {
            padding: 1rem 0;
        }

        .nav-item {
            padding: 1rem 1.5rem;
            cursor: pointer;
            transition: background-color 0.3s;
            border-left: 3px solid transparent;
        }

        .nav-item:hover {
            background: rgba(255,255,255,0.1);
        }

        .nav-item.active {
            background: rgba(52, 152, 219, 0.2);
            border-left-color: #3498db;
        }

        .nav-icon {
            margin-right: 0.75rem;
            width: 20px;
            display: inline-block;
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            margin-left: 250px;
            padding: 2rem;
        }

        .content-header {
            background: white;
            padding: 1.5rem 2rem;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            margin-bottom: 2rem;
        }

        .page-title {
            font-size: 2rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .page-description {
            color: #7f8c8d;
        }

        .content-section {
            display: none;
            animation: fadeIn 0.3s ease-in;
        }

        .content-section.active {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* 仪表板统计卡片 */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            padding: 2rem;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            text-align: center;
            transition: transform 0.3s;
        }

        .stat-card:hover {
            transform: translateY(-2px);
        }

        .stat-icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #3498db;
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: #7f8c8d;
            font-weight: 500;
        }

        /* 数据表格 */
        .data-table-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            overflow: hidden;
            margin-bottom: 2rem;
        }

        .table-header {
            background: #f8f9fa;
            padding: 1.5rem 2rem;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .table-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .add-btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .add-btn:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th,
        .data-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #f1f3f4;
        }

        .data-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }

        .data-table tr:hover {
            background: #f8f9fa;
        }

        .action-btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.875rem;
            font-weight: 500;
            margin-right: 0.5rem;
            transition: all 0.3s;
        }

        .edit-btn {
            background: #f39c12;
            color: white;
        }

        .edit-btn:hover {
            background: #e67e22;
        }

        .delete-btn {
            background: #e74c3c;
            color: white;
        }

        .delete-btn:hover {
            background: #c0392b;
        }

        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            animation: fadeIn 0.3s ease-in;
        }

        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            position: relative;
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .close {
            position: absolute;
            right: 1rem;
            top: 1rem;
            font-size: 1.5rem;
            cursor: pointer;
            color: #7f8c8d;
        }

        .close:hover {
            color: #2c3e50;
        }

        .modal-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 1.5rem;
            color: #2c3e50;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #2c3e50;
        }

        .form-input,
        .form-select,
        .form-textarea {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }

        .form-input:focus,
        .form-select:focus,
        .form-textarea:focus {
            outline: none;
            border-color: #3498db;
        }

        .form-textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background: #2980b9;
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn-secondary:hover {
            background: #7f8c8d;
        }

        /* 消息提示 */
        .message {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            text-align: center;
            display: none;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s;
            }

            .sidebar.open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
                padding: 1rem;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .table-header {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }

            .data-table {
                font-size: 0.875rem;
            }

            .modal-content {
                margin: 10% auto;
                width: 95%;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <div class="admin-title"> 管理后台</div>
                <div class="admin-subtitle" id="adminUsername">管理员</div>
            </div>
            <nav class="sidebar-nav">
                <div class="nav-item active" data-section="dashboard">
                    <span class="nav-icon"></span>仪表板
                </div>
                <div class="nav-item" data-section="products">
                    <span class="nav-icon"></span>商品管理
                </div>
                <div class="nav-item" data-section="users">
                    <span class="nav-icon"></span>用户管理
                </div>
                <div class="nav-item" data-section="orders">
                    <span class="nav-icon"></span>订单管理
                </div>
                <div class="nav-item" onclick="logout()">
                    <span class="nav-icon"></span>退出登录
                </div>
            </nav>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content">
            <div id="message" class="message"></div>

            <!-- 仪表板 -->
            <div id="dashboard" class="content-section active">
                <div class="content-header">
                    <h1 class="page-title">仪表板</h1>
                    <p class="page-description">查看系统概览和统计信息</p>
                </div>

                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon"></div>
                        <div class="stat-value" id="totalProducts">0</div>
                        <div class="stat-label">商品总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"></div>
                        <div class="stat-value" id="totalUsers">0</div>
                        <div class="stat-label">用户总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"></div>
                        <div class="stat-value" id="totalOrders">0</div>
                        <div class="stat-label">订单总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"></div>
                        <div class="stat-value" id="totalRevenue">¥0</div>
                        <div class="stat-label">总营收</div>
                    </div>
                </div>
            </div>

            <!-- 商品管理 -->
            <div id="products" class="content-section">
                <div class="content-header">
                    <h1 class="page-title">商品管理</h1>
                    <p class="page-description">管理商城中的所有商品</p>
                </div>


                <div class="data-table-container">
                    <div class="table-header">
                        <div class="table-title">商品列表</div>
                        <button class="add-btn" onclick="openProductModal()">添加商品</button>
                    </div>
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>商品名称</th>
                                <th>品牌</th>
                                <th>价格</th>
                                <th>库存</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="productsTableBody">
                            <!-- 商品数据将在这里动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 用户管理 -->
            <div id="users" class="content-section">
                <div class="content-header">
                    <h1 class="page-title">用户管理</h1>
                    <p class="page-description">管理平台用户</p>
                </div>

                <div class="data-table-container">
                    <div class="table-header">
                        <div class="table-title">用户列表</div>
                        <button class="add-btn" onclick="openUserModal()">添加用户</button>
                    </div>
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>用户类型</th>
                                <th>注册时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="usersTableBody">
                            <!-- 用户数据将在这里动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 订单管理 -->
            <div id="orders" class="content-section">
                <div class="content-header">
                    <h1 class="page-title">订单管理</h1>
                    <p class="page-description">查看和管理所有订单</p>
                </div>

                <div class="data-table-container">
                    <div class="table-header">
                        <div class="table-title">订单列表</div>
                    </div>
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>订单ID</th>
                                <th>用户</th>
                                <th>商品</th>
                                <th>数量</th>
                                <th>总价</th>
                                <th>下单时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="ordersTableBody">
                            <!-- 订单数据将在这里动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 商品模态框 -->
    <div id="productModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeProductModal()">&times;</span>
            <h2 class="modal-title" id="productModalTitle">添加商品</h2>
            <form id="productForm">
                <input type="hidden" id="productId">
                <div class="form-group">
                    <label class="form-label">商品名称</label>
                    <input type="text" class="form-input" id="productName" required>
                </div>
                <div class="form-group">
                    <label class="form-label">商品品牌</label>
                    <input type="text" class="form-input" id="productBrand" required>
                </div>
                <div class="form-group">
                    <label class="form-label">商品价格</label>
                    <input type="number" class="form-input" id="productPrice" step="0.01" required>
                </div>
                <div class="form-group">
                    <label class="form-label">库存数量</label>
                    <input type="number" class="form-input" id="stockQuantity" required>
                </div>
                <div class="form-group">
                    <label class="form-label">商品描述</label>
                    <textarea class="form-textarea" id="productDescription"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">商品状态</label>
                    <select class="form-select" id="productStatus">
                        <option value="1">上架</option>
                        <option value="0">下架</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeProductModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 用户模态框 -->
    <div id="userModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeUserModal()">&times;</span>
            <h2 class="modal-title" id="userModalTitle">添加用户</h2>
            <form id="userForm">
                <input type="hidden" id="userId">
                <div class="form-group">
                    <label class="form-label">用户名</label>
                    <input type="text" class="form-input" id="username" required>
                </div>
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <input type="password" class="form-input" id="password" required>
                </div>
                <div class="form-group">
                    <label class="form-label">用户类型</label>
                    <select class="form-select" id="isAdmin">
                        <option value="false">普通用户</option>
                        <option value="true">管理员</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeUserModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let currentAdmin = null;
        let products = [];
        let users = [];
        let orders = [];

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeAuth();
            initializeNavigation();
            loadDashboardData();
        });

        // 初始化认证状态
        function initializeAuth() {
            const userData = localStorage.getItem('currentUser');
            if (userData) {
                currentAdmin = JSON.parse(userData);
                if (!currentAdmin.isAdmin) {
                    showMessage('没有管理员权限', 'error');
                    setTimeout(() => {
                        window.location.href = 'index.html';
                    }, 2000);
                    return;
                }
                document.getElementById('adminUsername').textContent = currentAdmin.username;
            } else {
                window.location.href = 'login.html';
            }
        }

        // 初始化导航
        function initializeNavigation() {
            const navItems = document.querySelectorAll('.nav-item[data-section]');
            navItems.forEach(item => {
                item.addEventListener('click', function() {
                    const section = this.dataset.section;
                    switchSection(section);
                    
                    // 更新活动状态
                    navItems.forEach(nav => nav.classList.remove('active'));
                    this.classList.add('active');
                });
            });
        }

        // 切换内容区域
        function switchSection(section) {
            // 隐藏所有内容区域
            document.querySelectorAll('.content-section').forEach(el => {
                el.classList.remove('active');
            });
            
            // 显示目标区域
            document.getElementById(section).classList.add('active');
            
            // 加载对应数据
            switch(section) {
                case 'dashboard':
                    loadDashboardData();
                    break;
                case 'products':
                    loadProducts();
                    break;
                case 'users':
                    loadUsers();
                    break;
                case 'orders':
                    loadOrders();
                    break;
            }
        }

        // 加载仪表板数据
        async function loadDashboardData() {
            try {
                const [productsRes, usersRes, ordersRes] = await Promise.all([
                    fetch('/products'),
                    fetch('/users'),
                    fetch('/orders')
                ]);

                if (productsRes.ok) {
                    products = await productsRes.json();
                    document.getElementById('totalProducts').textContent = products.length;
                }

                if (usersRes.ok) {
                    users = await usersRes.json();
                    document.getElementById('totalUsers').textContent = users.length;
                }

                if (ordersRes.ok) {
                    orders = await ordersRes.json();
                    document.getElementById('totalOrders').textContent = orders.length;
                    
                    // 计算总营收
                    let totalRevenue = 0;
                    for (const order of orders) {
                        const product = products.find(p => p.productId === order.productId);
                        if (product) {
                            totalRevenue += product.productPrice * order.quantity;
                        }
                    }
                    document.getElementById('totalRevenue').textContent = `¥${totalRevenue.toFixed(2)}`;
                }
            } catch (error) {
                console.error('加载仪表板数据错误:', error);
                showMessage('加载数据失败', 'error');
            }
        }

        // 加载商品数据
        async function loadProducts() {
            try {
                const response = await fetch('/products');
                if (response.ok) {
                    products = await response.json();
                    renderProductsTable();
                } else {
                    showMessage('加载商品失败', 'error');
                }
            } catch (error) {
                console.error('加载商品错误:', error);
                showMessage('网络错误', 'error');
            }
        }

        // 渲染商品表格
        function renderProductsTable() {
            const tbody = document.getElementById('productsTableBody');
            tbody.innerHTML = '';

            products.forEach(product => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${product.productId}</td>
                    <td>${product.productName}</td>
                    <td>${product.productBrand || '未知'}</td>
                    <td>¥${product.productPrice.toFixed(2)}</td>
                    <td>${product.stockQuantity}</td>
                    <td>${product.productStatus === 1 ? '上架' : '下架'}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="editProduct(${product.productId})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteProduct(${product.productId})">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        // 加载用户数据
        async function loadUsers() {
            try {
                const response = await fetch('/users');
                if (response.ok) {
                    users = await response.json();
                    renderUsersTable();
                } else {
                    showMessage('加载用户失败', 'error');
                }
            } catch (error) {
                console.error('加载用户错误:', error);
                showMessage('网络错误', 'error');
            }
        }

        // 渲染用户表格
        function renderUsersTable() {
            const tbody = document.getElementById('usersTableBody');
            tbody.innerHTML = '';

            users.forEach(user => {
                const row = document.createElement('tr');
                const createTime = user.createTime ? new Date(user.createTime).toLocaleDateString() : '未知';
                row.innerHTML = `
                    <td>${user.userId}</td>
                    <td>${user.username}</td>
                    <td>${user.admin ? '管理员' : '普通用户'}</td>
                    <td>${createTime}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="editUser(${user.userId})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteUser(${user.userId})">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        // 加载订单数据
        async function loadOrders() {
            try {
                const response = await fetch('/orders');
                if (response.ok) {
                    orders = await response.json();
                    renderOrdersTable();
                } else {
                    showMessage('加载订单失败', 'error');
                }
            } catch (error) {
                console.error('加载订单错误:', error);
                showMessage('网络错误', 'error');
            }
        }

        // 渲染订单表格
        function renderOrdersTable() {
            const tbody = document.getElementById('ordersTableBody');
            tbody.innerHTML = '';

            orders.forEach(order => {
                const user = users.find(u => u.userId === order.userId);
                const product = products.find(p => p.productId === order.productId);
                const totalPrice = product ? (product.productPrice * order.quantity).toFixed(2) : '0.00';
                const createTime = order.createTime ? new Date(order.createTime).toLocaleDateString() : '未知';

                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${order.orderId}</td>
                    <td>${user ? user.username : '未知用户'}</td>
                    <td>${product ? product.productName : '未知商品'}</td>
                    <td>${order.quantity}</td>
                    <td>¥${totalPrice}</td>
                    <td>${createTime}</td>
                    <td>
                        <button class="action-btn delete-btn" onclick="deleteOrder(${order.orderId})">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        // 商品管理功能
        function openProductModal(productId = null) {
            const modal = document.getElementById('productModal');
            const form = document.getElementById('productForm');
            const title = document.getElementById('productModalTitle');

            if (productId) {
                // 编辑模式
                const product = products.find(p => p.productId === productId);
                if (product) {
                    title.textContent = '编辑商品';
                    document.getElementById('productId').value = product.productId;
                    document.getElementById('productName').value = product.productName;
                    document.getElementById('productBrand').value = product.productBrand || '';
                    document.getElementById('productPrice').value = product.productPrice;
                    document.getElementById('stockQuantity').value = product.stockQuantity;
                    document.getElementById('productDescription').value = product.productDescription || '';
                    document.getElementById('productStatus').value = product.productStatus;
                }
            } else {
                // 添加模式
                title.textContent = '添加商品';
                form.reset();
                document.getElementById('productId').value = '';
            }

            modal.style.display = 'block';
        }

        function closeProductModal() {
            document.getElementById('productModal').style.display = 'none';
        }

        function editProduct(productId) {
            openProductModal(productId);
        }

        async function deleteProduct(productId) {
            if (!confirm('确定要删除这个商品吗？')) return;

            try {
                const response = await fetch(`/products/${productId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    showMessage('商品删除成功', 'success');
                    loadProducts();
                } else {
                    showMessage('删除失败', 'error');
                }
            } catch (error) {
                console.error('删除商品错误:', error);
                showMessage('网络错误', 'error');
            }
        }

        // 处理商品表单提交
        document.getElementById('productForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const productId = document.getElementById('productId').value;
            const productData = {
                productName: document.getElementById('productName').value,
                productBrand: document.getElementById('productBrand').value,
                productPrice: parseFloat(document.getElementById('productPrice').value),
                stockQuantity: parseInt(document.getElementById('stockQuantity').value),
                productDescription: document.getElementById('productDescription').value,
                productStatus: parseInt(document.getElementById('productStatus').value)
            };

            if (productId) {
                productData.productId = parseInt(productId);
            }

            try {
                const method = productId ? 'PUT' : 'POST';
                const response = await fetch('/products', {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(productData)
                });

                if (response.ok) {
                    showMessage(productId ? '商品更新成功' : '商品添加成功', 'success');
                    closeProductModal();
                    loadProducts();
                } else {
                    showMessage('保存失败', 'error');
                }
            } catch (error) {
                console.error('保存商品错误:', error);
                showMessage('网络错误', 'error');
            }
        });

        // 用户管理功能
        function openUserModal(userId = null) {
            const modal = document.getElementById('userModal');
            const form = document.getElementById('userForm');
            const title = document.getElementById('userModalTitle');

            if (userId) {
                // 编辑模式
                const user = users.find(u => u.userId === userId);
                if (user) {
                    title.textContent = '编辑用户';
                    document.getElementById('userId').value = user.userId;
                    document.getElementById('username').value = user.username;
                    document.getElementById('password').value = ''; // 编辑时不显示密码
                    document.getElementById('isAdmin').value = user.admin ? 'true' : 'false';
                }
            } else {
                // 添加模式
                title.textContent = '添加用户';
                form.reset();
                document.getElementById('userId').value = '';
            }

            modal.style.display = 'block';
        }

        function closeUserModal() {
            document.getElementById('userModal').style.display = 'none';
        }

        function editUser(userId) {
            openUserModal(userId);
        }

        async function deleteUser(userId) {
            if (userId === currentAdmin.userId) {
                showMessage('不能删除当前登录的管理员账号', 'error');
                return;
            }

            if (!confirm('确定要删除这个用户吗？')) return;

            try {
                const response = await fetch(`/users/${userId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    showMessage('用户删除成功', 'success');
                    loadUsers();
                } else {
                    showMessage('删除失败', 'error');
                }
            } catch (error) {
                console.error('删除用户错误:', error);
                showMessage('网络错误', 'error');
            }
        }

        // 处理用户表单提交
        document.getElementById('userForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const userId = document.getElementById('userId').value;
            const userData = {
                username: document.getElementById('username').value,
                admin: document.getElementById('isAdmin').value === 'true'
            };

            const password = document.getElementById('password').value;
            if (password) {
                userData.password = password;
            }

            if (userId) {
                userData.userId = parseInt(userId);
            }

            try {
                const method = userId ? 'PUT' : 'POST';
                const response = await fetch('/users', {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(userData)
                });

                if (response.ok) {
                    showMessage(userId ? '用户更新成功' : '用户添加成功', 'success');
                    closeUserModal();
                    loadUsers();
                } else {
                    showMessage('保存失败', 'error');
                }
            } catch (error) {
                console.error('保存用户错误:', error);
                showMessage('网络错误', 'error');
            }
        });

        // 订单管理功能
        async function deleteOrder(orderId) {
            if (!confirm('确定要删除这个订单吗？')) return;

            try {
                const response = await fetch(`/orders/${orderId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    showMessage('订单删除成功', 'success');
                    loadOrders();
                } else {
                    showMessage('删除失败', 'error');
                }
            } catch (error) {
                console.error('删除订单错误:', error);
                showMessage('网络错误', 'error');
            }
        }

        // 显示消息
        function showMessage(text, type = 'success') {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;
            messageEl.className = `message ${type}`;
            messageEl.style.display = 'block';

            setTimeout(() => {
                messageEl.style.display = 'none';
            }, 5000);
        }

        // 登出
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('currentUser');
                window.location.href = 'login.html';
            }
        }

        // 关闭模态框的点击事件
        window.onclick = function(event) {
            const productModal = document.getElementById('productModal');
            const userModal = document.getElementById('userModal');
            
            if (event.target === productModal) {
                closeProductModal();
            }
            if (event.target === userModal) {
                closeUserModal();
            }
        }
    </script>
</body>
</html> 